package cn.gs.exchanger.agent;

// @author gs
import cn.gs.serializable.entity.IEntity;
import cn.gs.serializable.entity.MapEntity;
import cn.gs.serializable.entity.OneEntity;
import cn.gs.serializable.serialize.ISerialize;
import cn.gs.serializable.serialize.StringSerialize;
import cn.gs.reflect.ProxyTool;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class ClientAgentSerialize implements ISerialize {

    AgentClient manager;
    StringSerialize strs = new StringSerialize();

    public ClientAgentSerialize(AgentClient manager) {
        this.manager = manager;
    }

    @Override
    public <T> T toObj(ISerialize ctrl, IEntity from, Class<T> clazz) {
        if (manager.cls.contains(clazz) && from instanceof MapEntity) {
            Map<String, IEntity> m = null;
            //Map MapEntity
            if (null == m) {
                m = new HashMap<String, IEntity>();
                for (Map.Entry<IEntity, IEntity> e : ((MapEntity) from).getMap().entrySet()) {
                    String k = strs.toObj(ctrl, e.getKey(), String.class);
                    m.put(k, e.getValue());
                }
            }
            //Create Agent
            String id = strs.toObj(ctrl, m.get(CAgent.SERIALIZE_ID), String.class);
            String server = strs.toObj(ctrl, m.get(CAgent.SERIALIZE_SERVER), String.class);
            if (id != null && server != null) {
                Agent p = new Agent(id, server, manager, clazz);
                return (T) p.proxyObject();
            }
        }
        return null;
    }

    @Override
    public IEntity fromObj(ISerialize ctrl, Object o) {
        if (o != null) {
            Object target = ProxyTool.getProxyTarget(o);
            if (target != null && target instanceof Agent) {
                Agent agent = (Agent) target;
                if (manager.cls.contains(agent.forProxy)) {
                    MapEntity e = new MapEntity();
                    e.getMap().put(new OneEntity(CAgent.SERIALIZE_ID, true), new OneEntity(agent.getId(), true));
                    e.getMap().put(new OneEntity(CAgent.SERIALIZE_SERVER, true), new OneEntity(agent.getServer(), true));
                    return e;
                }
            }
        }
        return null;
    }
}
